package org.meeting.radish.util;

import org.meeting.radish.entity.TestCase;
import org.meeting.radish.entity.UserAnswer;
import org.meeting.radish.oj.CodeTypeException;
import org.meeting.radish.oj.OjParameter;
import org.meeting.radish.oj.OjService;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class OjUtil {

    private final OjService ojService;
    private Map<String, String> orders;

    public static OjUtil getOjUtil(UserAnswer answer, String language, String code) throws CodeTypeException, IOException {
        return new OjUtil(answer, language, code);
    }

    private OjUtil(UserAnswer answer, String language, String code) throws CodeTypeException, IOException {
        ojService = new OjService(String.format("%d_%d", answer.getUid(), answer.getQid()), code, language);
        init();
    }

    private void init() throws CodeTypeException, IOException {
        ojService.saveCodeFile();
        orders = ojService.getCompileAndRunOrder();
    }

    public Map<Boolean, String> run(List<TestCase> testCases) throws IOException {
        Map<Boolean, String> result = new HashMap<>();

        String run = orders.get(OjParameter.OjExecute.RUN);
        for (TestCase testCase : testCases) {
            Map<Boolean, String> runResult = ojService.run(run, testCase.getIn(), testCase.getOut());
            result.putAll(runResult);
        }
        return result;
    }

    public Map<Boolean, String> compile() throws IOException, InterruptedException {
        String compile = orders.get(OjParameter.OjExecute.COMPILE);
        return ojService.compile(compile);
    }

}
